using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using hao_Dto.User;
using hao_Common.Response.Extensions;
using User.Service.Address;
using System.Security.Claims;

namespace hao_User.Api.Controllers
{
    [ApiController]
    [Route("api/address")]
    [Authorize]
    public class AddressController : ControllerBase
    {
        private readonly IAddressService _addressService;
        private readonly ILogger<AddressController> _logger;

        public AddressController(IAddressService addressService, ILogger<AddressController> logger)
        {
            _addressService = addressService;
            _logger = logger;
        }

        /// <summary>
        /// 创建地址
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> CreateAddress([FromBody] CreateAddressDto createAddressDto)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId == Guid.Empty)
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var result = await _addressService.CreateAddressAsync(userId, createAddressDto);
                return this.SuccessResult(result, "地址创建成功");
            }
            catch (InvalidOperationException ex)
            {
                return this.FailResult(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建地址失败");
                return this.ServerErrorResult($"创建地址失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新地址
        /// </summary>
        [HttpPost("update/{id}")]
        public async Task<IActionResult> UpdateAddress(Guid id, [FromBody] UpdateAddressDto updateAddressDto)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId == Guid.Empty)
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var result = await _addressService.UpdateAddressAsync(id, userId, updateAddressDto);
                if (result)
                {
                    return this.SuccessResult("地址更新成功");
                }
                return this.FailResult("地址更新失败");
            }
            catch (InvalidOperationException ex)
            {
                return this.FailResult(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新地址失败");
                return this.ServerErrorResult($"更新地址失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除地址
        /// </summary>
        [HttpPost("delete/{id}")]
        public async Task<IActionResult> DeleteAddress(Guid id)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId == Guid.Empty)
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var result = await _addressService.DeleteAddressAsync(id, userId);
                if (result)
                {
                    return this.SuccessResult("地址删除成功");
                }
                return this.FailResult("地址删除失败");
            }
            catch (InvalidOperationException ex)
            {
                return this.FailResult(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除地址失败");
                return this.ServerErrorResult($"删除地址失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取当前用户地址列表
        /// </summary>
        [HttpGet("list")]
        public async Task<IActionResult> GetMyAddresses()
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId == Guid.Empty)
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var result = await _addressService.GetUserAddressesAsync(userId);
                return this.SuccessResult(result, "获取地址列表成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取地址列表失败");
                return this.ServerErrorResult($"获取地址列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取当前用户默认地址
        /// </summary>
        [HttpGet("default")]
        public async Task<IActionResult> GetDefaultAddress()
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId == Guid.Empty)
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var result = await _addressService.GetDefaultAddressAsync(userId);
                if (result != null)
                {
                    return this.SuccessResult(result, "获取默认地址成功");
                }
                return this.NotFoundResult("未设置默认地址");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取默认地址失败");
                return this.ServerErrorResult($"获取默认地址失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 调试：获取所有地址信息（临时接口）
        /// </summary>
        [HttpGet("debug/all")]
        public async Task<IActionResult> DebugGetAllAddresses()
        {
            try
            {
                var userId = GetCurrentUserId();
                _logger.LogInformation($"调试接口 - 当前用户ID: {userId}");
                
                if (userId == Guid.Empty)
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var allAddresses = await _addressService.GetUserAddressesAsync(userId);
                return this.SuccessResult(new { 
                    CurrentUserId = userId,
                    AddressCount = allAddresses.Count,
                    Addresses = allAddresses.Select(a => new {
                        a.Id,
                        a.UserId, 
                        a.ReceiverName,
                        a.Status,
                        a.IsDefault
                    })
                }, "调试信息获取成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "调试接口失败");
                return this.ServerErrorResult($"调试接口失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取地址详情
        /// </summary>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetAddress(Guid id)
        {
            try
            {
                var userId = GetCurrentUserId();
                _logger.LogInformation($"获取地址详情: AddressId={id}, UserId={userId}");
                
                if (userId == Guid.Empty)
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var result = await _addressService.GetAddressByIdAsync(id, userId);
                if (result != null)
                {
                    return this.SuccessResult(result, "获取地址成功");
                }
                _logger.LogWarning($"地址不存在或无权限访问: AddressId={id}, UserId={userId}");
                return this.NotFoundResult("地址不存在");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取地址失败");
                return this.ServerErrorResult($"获取地址失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 设置默认地址
        /// </summary>
        [HttpPost("set-default/{id}")]
        public async Task<IActionResult> SetDefaultAddress(Guid id)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId == Guid.Empty)
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var result = await _addressService.SetDefaultAddressAsync(userId, id);
                if (result)
                {
                    return this.SuccessResult("设置默认地址成功");
                }
                return this.FailResult("设置默认地址失败");
            }
            catch (InvalidOperationException ex)
            {
                return this.FailResult(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置默认地址失败");
                return this.ServerErrorResult($"设置默认地址失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量删除地址
        /// </summary>
        [HttpPost("batch-delete")]
        public async Task<IActionResult> BatchDeleteAddresses([FromBody] List<Guid> addressIds)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId == Guid.Empty)
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                if (addressIds == null || addressIds.Count == 0)
                {
                    return this.FailResult("请选择要删除的地址");
                }

                var result = await _addressService.BatchDeleteAddressesAsync(addressIds, userId);
                if (result)
                {
                    return this.SuccessResult("批量删除地址成功");
                }
                return this.FailResult("批量删除地址失败");
            }
            catch (InvalidOperationException ex)
            {
                return this.FailResult(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除地址失败");
                return this.ServerErrorResult($"批量删除地址失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 搜索地址（管理员功能）
        /// </summary>
        [HttpPost("search")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> SearchAddresses([FromBody] AddressSearchDto searchDto)
        {
            try
            {
                if (searchDto.PageSize <= 0) searchDto.PageSize = 10;
                if (searchDto.PageNumber <= 0) searchDto.PageNumber = 1;

                var (addresses, totalCount) = await _addressService.SearchAddressesAsync(searchDto);
                return this.PagedResult(addresses, searchDto.PageNumber, searchDto.PageSize, totalCount, "搜索地址成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索地址失败");
                return this.ServerErrorResult($"搜索地址失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取地址区域统计（管理员功能）
        /// </summary>
        [HttpGet("stats/region")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> GetRegionStats()
        {
            try
            {
                var result = await _addressService.GetRegionStatsAsync();
                return this.SuccessResult(result, "获取区域统计成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取区域统计失败");
                return this.ServerErrorResult($"获取区域统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 导出用户地址
        /// </summary>
        [HttpGet("export")]
        public async Task<IActionResult> ExportAddresses()
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId == Guid.Empty)
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var result = await _addressService.ExportUserAddressesAsync(userId);
                return this.SuccessResult(result, "导出地址成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出地址失败");
                return this.ServerErrorResult($"导出地址失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 导入地址数据（管理员功能）
        /// </summary>
        [HttpPost("import")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> ImportAddresses([FromBody] List<ImportAddressDto> addresses)
        {
            try
            {
                if (addresses == null || addresses.Count == 0)
                {
                    return this.FailResult("请提供要导入的地址数据");
                }

                var (successCount, failCount, errors) = await _addressService.ImportAddressesAsync(addresses);
                
                var result = new
                {
                    SuccessCount = successCount,
                    FailCount = failCount,
                    Errors = errors,
                    Total = addresses.Count
                };

                return this.SuccessResult(result, $"导入完成：成功 {successCount} 条，失败 {failCount} 条");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导入地址失败");
                return this.ServerErrorResult($"导入地址失败: {ex.Message}");
            }
        }

        #region 私有方法

        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        private Guid GetCurrentUserId()
        {
            var userIdClaim = User.FindFirst("UserId")?.Value;
            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out Guid userId))
            {
                return Guid.Empty;
            }
            return userId;
        }

        #endregion
    }
}